<?php
namespace Api\Controller;
use Think\Controller;
class PayController extends Controller{
	//自动加载ping++第三方文件
	public function _initialize(){
		vendor("Pingpp.init");
	}
	//用户支付
		//用ping++，返回charge数据
	public function pay(){
		$input_data = $_POST;
		if (empty($input_data['channel']) || empty($input_data['amount'])) {
			die(json_encode("empty"));
		}
		$channel = strtolower($input_data['channel']);
		$amount = $input_data['amount'];
		$orderNo = substr(md5(time()), 0, 12);
		$body = $input_data["body"];
		$subject = $input_data["subject"];
		//$extra 在使用某些渠道的时候，需要填入相应的参数，其它渠道则是 array() .具体见以下代码或者官网中的文档。其他渠道时可以传空值也可以不传。
		$extra = array();
		switch ($channel) {
		
			case 'alipay_wap':
				$extra = array(
				'success_url' => C("__PAYURL__").'paysuccess',
				'cancel_url' => C("__PAYURL__").'paycancel'
						);
						break;
			case 'upmp_wap':
				$extra = array(
				'result_url' => C("__PAYURL__").'Webhooks'
						);
						break;
			case 'bfb_wap':
				$extra = array(
				'result_url' => C("__PAYURL__").'Webhooks',
				'bfb_login' => true
				);
				break;
			case 'upacp_wap':
				$extra = array(
				'result_url' => C("__PAYURL__").'Webhooks'
						);
						break;
			case 'wx_pub':
				$extra = array(
				'open_id' => 'Openid'
						);
						break;
			case 'wx_pub_qr':
				$extra = array(
				'product_id' => 'Productid'
						);
						break;
		}
			
		\Pingpp\Pingpp::setApiKey(C('__PAYKEY__'));
		try {
			$ch = \Pingpp\Charge::create(
					array(
							'subject'   => $subject,
							'body'      => $body,
							'amount'    => $amount,
							'order_no'  => $orderNo,
							'currency'  => 'cny',
							'extra'     => $extra,
							'channel'   => $channel,
							'client_ip' => $_SERVER['REMOTE_ADDR'],
							'app'       => array('id' => C('__APPID__'))
					)
			);
			header("Content-Type: text/json");
			echo $ch;
				
		} catch (\Pingpp\Error\Base $e) {
			header('Status: ' . $e->getHttpStatus());
			echo($e->getHttpBody());
		}
			
		$this->buildOrder($ch, $input_data);
	}
	public function buildOrder($ch,$input_data){
			$data = (array)json_decode($ch);
			//获取数据，新增数据
			$order = M("Order");
			//用户商店商品id
			$order->user_id = $input_data['user_id'];
			$order->task_id = $input_data['task_id'];
			$order->city_id = $input_data['city_id'];
			
			//支付信息
			$order->charge_id = $data["id"];
			$order->pay_type = $data['channel'];//支付类型
			$order->payment_trade_no = $data['id'];//支付接口交易号
			$order->payment_trade_status = "";//支付交易状态
			$order->pay_time = $input_data['time_paid'];//支付时间
			//订单详情
			$order->pay_price = $data['amount'];//总金额
			$order->subject = $data['subject'];//名称
			$order->body = $data["body"];
			$order->pay_order_no = $data['order_no'];
			
			$order->create_time = time();//订单创建时间
			//增加订单
			$order->add();
		
		
	}
		//webhooks返回
	public function Webhooks(){
	
		$event = json_decode(file_get_contents('php://input'),true);
		// 对异步通知做处理
		if (!isset($event['type'])) {
			header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
			exit("fail");
		}
		switch ($event['type']) {
			case "charge.succeeded":
				// 对支付异步通知的处理
				$this->paysucc($event);
				header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
				break;
			case "refund.succeeded":
				// 开发者在此处加入对退款异步通知的处理代码
				header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
				break;
			default:
				$this->paycancel($event);
				header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
				break;
		}
	
	}
	public function paysucc($event=null){
		$order = M("Order");
		$order_no = $event['data']["object"]['order_no'];
		$order->statue = "pay";
		$order->pay_time = $event['data']["object"]['time_paid'];//支付时间
		
		if($order->where("pay_order_no = '$order_no'")->save()){
			$task_id = $order->where("pay_order_no = '$order_no'")->field("task_id")->find()["task_id"];
			M("Task")->pay_status = "pay";
			M("Task")->where("id = $task_id")->save();
			$code=["pay" =>"success"];
			header("Content-Type: text/json");
			die(json_encode($code));
		}else{
			$code=["pay" =>"worng"];
			header("Content-Type: text/json");
			die(json_encode($code));
		}
		

	}
	//支付失败
	public function paycancel($input_data=null){
		//接收数据
	
		//修改数据库
		if($input_data == null){
			$input_data = json_decode(file_get_contents('php://input'), true);
		}
		if($input_data['type'] == 'charge.succeeded')
		{
			$order = M("Order");
			$order->statue = "cancel";
			$order_no =  $input_data['data']["object"]['id'];
			
			$order->pay_time = $input_data['data']["object"]['time_paid'];//支付时间
			if($order->where("payment_trade_no = $order_no")->save()){
				$code=["cancel" =>"success"];
				header("Content-Type: text/json");
				die(json_encode($code));
			}else{
				$code=["cancel" =>"wrong"];
				header("Content-Type: text/json");
				die(json_encode($code));
			}
				
				
		}
	}
	//安装工提现
	public function applyCash(){
		$applycash  = M("Applycash");
		$applycash->money = $_POST["money"];
		$applycash->erector_id = $_POST["erector_id"];
		$applycash->account_type = $_POST["account_type"];
		$applycash->account_num  = $_POST["account_num"];
		$applycash->apply_time = time();
		if($applycash->add()){
			$code=["apply" =>"success"];
			header("Content-Type: text/json");
			die(json_encode($code));
		}else{
			$code=["apply" =>"wrong"];
			header("Content-Type: text/json");
			die(json_encode($code));
		}
		
	}
	

}